<template>
  <div>
    <div>
      <ele-page
        v-loading="loading"
        :formConfig="searchConfig"
        ref="eleTable"
        :column="column"
        :operateList="operateList"
        @handleOperateEvent="handleOperateEvent"
        :getList="getList"
        uniqueId="wmsInTaskTable"
      >
      </ele-page>
    </div>
    <ele-form-drawer
      :isLoading="isLoading"
      v-model="formDataDialog"
      v-bind="formDescDialog"
      :isShowBackBtn="false"
      :isShowSubmitBtn="false"
      :request-fn="handleSubmit"
      :visible.sync="visible"
      :title="title"
      size="75%"
    >
      <template v-slot:vinCode>
        <el-input v-model="formDataDialog.vinCode"
                  readonly
                  :disabled = "!!formDataDialog.id"
                  placeholder='请选择车辆'>
          <el-button
            :disabled = "!!formDataDialog.id"
            slot="append"
            icon="el-icon-search"
            @click="mixinDialogVisible = true"></el-button>
        </el-input>
      </template>
      <template v-slot:mesKtInTaskDetailVos>
<!--        <el-button-->
<!--          type="primary"-->
<!--          slot="append"-->
<!--          icon="el-icon-search"-->
<!--          @click="addList">新增</el-button>-->
        <el-row type="flex" class="row-bg" justify="end">
          <el-button type="primary"
                     v-if="formDataDialog.id && formDataDialog.isFinish !== 'Y'"
                     @click="handleEditBatch({...formDataDialog})">批量入库</el-button>
        </el-row>
        <el-table
          :data="mesKtInTaskDetailVoList"
          style="width: 100%">
          <el-table-column
            prop="goodsCode"
            label="物料编码"
            width="180">
          </el-table-column>
          <el-table-column
            prop="goodsName"
            label="物料名称"
            width="180">
          </el-table-column>
          <el-table-column
            prop="brand"
            width="140"
            label="品牌">
            <template slot-scope="scope">
              <el-select v-model="scope.row.brand"
                         clearable
                         filterable
                         placeholder="请选择品牌"
                         :disabled="scope.row.realAmount > 0 || scope.row.brandOrg"
              >
                <el-option
                  v-for="dict in scope.row.mesTmMaterialBrandList"
                  :key="dict.brand"
                  :label="dict.brand"
                  :value="dict.brand">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            prop="unit"
            width="140"
            label="规格">
            <template slot-scope="scope">
              <el-select v-model="scope.row.unit"
                         clearable
                         filterable
                         placeholder="请选择规格"
                         :disabled="scope.row.realAmount > 0 || scope.row.unitOrg"
              >
                <el-option
                  v-for="dict in scope.row.mesTmMaterialUnitList"
                  :key="dict.unit"
                  :label="dict.unit"
                  :value="dict.unit">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            prop="planAmount"
            label="计划数"
            width="80">
          </el-table-column>
          <el-table-column
            prop="realAmount"
            label="已入库数"
            width="80">
          </el-table-column>
          <el-table-column
            prop="accountingAmount"
            label="入库数量"
            width="140">
            <template slot-scope="scope">
              <el-input-number
                :disabled = 'scope.row.planAmount === scope.row.realAmount'
                v-model="scope.row.accountingAmount"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column
            prop="packUnitShow"
            label="入库单位"
            width="80">
          </el-table-column>
          <el-table-column
            prop="materialTypeStr"
            width="120"
            label="物料类型">
            <template slot-scope="scope">
              <el-select v-model="scope.row.materialTypeStr"
                         clearable
                         filterable
                         placeholder="请选择物料类型"
                         :disabled="scope.row.realAmount > 0 || scope.row.materialTypeStrOrg"
              >
                <el-option
                  v-for="dict in materialTypeList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            prop="supplierName"
            label="供应商名称"
            width="240">
            <template slot-scope="scope">
              <el-select v-model="scope.row.supplierName"
                         clearable
                         filterable
                         placeholder="请选择供应商"
                         :disabled="scope.row.realAmount > 0 || scope.row.supplierNameOrg"
              >
                <el-option
                  v-for="dict in supplierNameList"
                  :key="dict.postName"
                  :label="dict.postName"
                  :value="dict.postName">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            prop="price"
            label="供应商报价"
            width="100">
          </el-table-column>
          <el-table-column label="操作"
                           width="120">
            <template slot-scope="scope">
              <el-button
                size="mini"
                :disabled = 'scope.row.planAmount === scope.row.realAmount'
                @click="handleEdit( scope.row)">{{scope.row.planAmount === scope.row.realAmount ? "已到货":"入库"}}</el-button>
              <!--<el-button-->
              <!--  size="mini"-->
              <!--  type="danger"-->
              <!--  @click="handleDelete(scope.$index, scope.row)">删除</el-button>-->
            </template>
          </el-table-column>
        </el-table>
      </template>
    </ele-form-drawer>

    <ele-dialog-table
      title="车辆订单列表"
      width="800px"
      :visible.sync="mixinDialogVisible"
      :formConfig="mixinSearchDialog"
      :column="mixinDialogColumn"
      @getSelectData="getSelectMixin"
      :getList="waitInTask"
      :hasFooter="hasMixinFooter"
    ></ele-dialog-table>

    <ele-dialog-table
      title="待入库物料"
      width="800px"
      :visible.sync="goodsDialogVisible"
      :formConfig="goodsSearchDialog"
      :column="goodsDialogColumn"
      @getSelectData="setSelectGoods"
      @handleOperateEvent="handleOperateEvent1"
      :getList="waitInTaskDetail"
      :hasFooter="goodsHasFooter"
        :otherParam="otherParam"
    >
    </ele-dialog-table>

  </div>
</template>

<script>
import { operateList, searchConfig, formDescDialog, rowConfig } from "./config";
import {
  getList,
  waitInTask,
  rowDel,
  getCurrentWarehouseCode,
  rowBatchCreate,
  getInfoByOrderNo,
  rowAccount, wmsKtInTaskDetail, mesTmMaterialBrand, createData, wmsKtInTaskDetailBatch,
} from "@/api/inbound/mesInTask";
import { goodsDialog } from "./mixinGoods";
import {getPostList} from "@/api/common";
import {uniqueKey} from "@/utils/judge";
export default {
  name: "wmsInTask",
  mixins: [ goodsDialog,formDescDialog],
  props: {
    typeInto: {
      type: Number | String,
      default: 0,
    },
  },
  data() {
    return {
      supplierNameList:[],
      materialTypeList: [{
        value: '原厂件',
        label: '原厂件'
      }, {
        value: '品牌件',
        label: '品牌件',
      }, {
        value: '其他',
        label: '其他'
      }, {
        value: '拆车件',
        label: '拆车件'
      }],
      mesKtInTaskDetailVoList:[],

      waitInTask,
      hasMixinFooter: true, // 是否需要底部按钮默认true
      mixinDialogColumn: [
        {
          type: "selection",
        },
        {
          type: "index",
          label: $i18n.t("common.order"),
          width: 60,
        },
        {
          prop: "orderCode",
          label: '车辆订单编号',
          showOverflowTooltip: true,
        },
        {
          prop: 'uwbCode',
          label: 'uwb编号',
          showOverflowTooltip: true
        },
        {
          prop: 'vinCode',
          label: 'vin编号',
          showOverflowTooltip: true
        }, {
          prop: 'modelName',
          label: '车型',
          showOverflowTooltip: true
        },
      ],
      mixinSearchDialog: {
        inline: true,
        formDesc: {
          searchNo: {
            type: "input",
            label: '编号',
          },
          modelName: {
            type: "input",
            label: '车型',
          },
        },
      },
      mixinDialogVisible:false,
      title: null,
      visible: false,
      isLoading: false,
      loading: false,
      formDataDialog: {},
      searchConfig,
      operateList,
      otherParam:{},
      getList,
      // 列表页字段的绑定配置
      column: [
        {
          type: "selection",
        },
        {
          type: "index",
          label: $i18n.t("common.order"),
          fixed: "left",
          width: 60,
        },
        {
          prop: "warehouseCode",
          columnKey: "warehouseName",
          label: $i18n.t("common.warehouseName"),
          width: 150,
          optionProp: {
            value: "modelingCode",
            label: "modelingName",
          },
          option: async (data) => {
            const res = await getCurrentWarehouseCode();
            let list = res.data.result || []
            list.forEach(val => {
              val.modelingName = `${val.modelingCode}-${val.modelingName}`
            });
            return list;
          },
        },
        {
          prop: "orderNo",
          label: "入库单据编码",
          width: 170,
          sortable: "custom",
        },
        {
          prop: "taskType",
          label: "入库类型",
          width: 80,
          render: (h, scope) => {
            let status = ''
            switch (scope.row.taskType) {
              case '1':
              // status = 24
              // break
              case '2':
                status = '普通入库'
                break
              case '3':
                status = '特殊入库'
                break
              case '4':
                status = '盘盈入库'
                break
            }
            return <div>{status}</div>
          },
        },
        {
          prop: "orderCode",
          label: "车辆订单编号",
          width: 160,
          showOverflowTooltip: true,
        },
        {
          prop: "uwbCode",
          label: "uwb编号",
          width: 120,
          showOverflowTooltip: true,
        },
        {
          prop: "vinCode",
          label: "VIN编码",
          width: 160,
        },
        {
          prop: "modelName",
          label: "车型名称",
          width: 120,
        },
        {
          prop: "detailCount",
          label: "物料数量",
          width: 120,
        },
        {
          prop: "finishCount",
          label: "完成入库数量",
          width: 120,
        },
        {
          prop: "createByName",
          label: $i18n.t("common.createByName"),
          width: 130,
        },
        {
          prop: "createTime",
          label: $i18n.t("common.createTime"),
          sortable: "custom",
          width: 170,
        },
        {
          prop: "updateByName",
          label: $i18n.t("common.updateByName"),
          width: 130,
        },
        {
          prop: "updateTime",
          label: $i18n.t("common.updateTime"),
          width: 170,
        },
        {
          prop: "operate",
          label: $i18n.t("common.operation"),
          width: 160,
          fixed: "right",
          render: (h, scope) => {
            return (
              <ele-row-operation
                scope={scope}
                rowConfig={rowConfig}
                onRowOperate={this.rowOperate}
              ></ele-row-operation>
            );
          },
        },
      ],
    };
  },
  computed: {},
  created() {
    getPostList().then(res=>{
      this.supplierNameList = res.data.result
      //postName
      console.log(res)
    })
  },
  methods: {
    test(row){
      console.log(row)
    },
    setSelectGoods(data) {
      // 调试完成记得删除控制台打印
      console.log("选中数据", data)
      data.map((ite) => {
        let b = false;
        this.mesKtInTaskDetailVoList.map((item)=>{
          console.log(item.goodsCode , ite.goodsCode , '11' )
          if(item.goodsCode === ite.goodsCode){
            b = true;
          }
        })
        if(!b){
          this.$set(this.mesKtInTaskDetailVoList, this.mesKtInTaskDetailVoList.length, ite);
        }
      })
    },
    addList() {
      if(!this.formDataDialog.vinCode){
        this.$message.error('请先选择车辆');
        return;
      }
      this.goodsDialogVisible = true
      this.otherParam={
        vinCode: this.formDataDialog.vinCode
      }
      console.log(this.formDataDialog,'shenmjoi')
    },
    getSelectMixin(data) {
      console.warn(data)
      // 筛选重复值,插入
      this.$set(this.formDataDialog, 'vinCode', data[0].vinCode)
      this.$set(this.formDataDialog, 'orderCode', data[0].orderCode)
      this.$set(this.formDataDialog, 'modelName', data[0].modelName)
      this.$set(this.formDataDialog, 'uwbCode', data[0].uwbCode)

      //根据VIN 直接获取所有的明细项
      //获取已保存的数据项，以及可能新增的数据项，参考报价单
      this.isLoading = true;
      createData(data[0])
        .then((res) => {
          const message = res.data.message;
          this.$message.success(message || $i18n.t("common.operateSuccess"));
          this.editInfo(res.data.result, false)
          this.refresh(true);
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    //表格顶部按钮操作事件
    handleOperateEvent({ handleName, name, rows }) {
      this.title = name;
      const fnc = {
        add: () => {
          this.changeMaster(false);
          this.formDataDialog = {};
          this.mesKtInTaskDetailVoList = [];
          this.visible = true;
        },
        batchAdd: () => {
          let pathParam = "/inbound/wmsInTaskAdd";
          this.$router.push({ path: pathParam });
        },
        delete: () => {
          this.$confirm(
            $i18n.t("wmsInTask.deleteBatch"),
            $i18n.t("common.tip"),
            {
              confirmButtonText: $i18n.t("common.ok"),
              cancelButtonText: $i18n.t("common.cancel"),
              type: "warning",
            }
          ).then(() => {
            const ids = rows.map((val) => val.id).join(",");
            this.rowDel(ids);
          });
        },
        account: () => {
          const ids = rows.map((val) => val.id).join(",");
          this.rowAccount(ids);
        },
      };
      fnc[handleName] && fnc[handleName]();
    },
    //表格行操作事件
    rowOperate({ handleName, name, row }) {
      this.title = name;
      const fnc = {
        edit: () => {
          // 修改详情，并打开界面
          this.editInfo(row.id, false);
        }
      };
      fnc[handleName] && fnc[handleName]();
    },
    //弹框提交事件
    handleSubmit(data) {
      if (this.isLoading) return; // 判断状态

      console.log(data)
      this.rowUpdate(data)
    },
    handleSubmitBatch(data) {
      if (this.isLoading) return; // 判断状态
      console.log(data)
      this.isLoading = true;
      wmsKtInTaskDetailBatch(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(message || $i18n.t("common.operateSuccess"));
          this.editInfo(res.data.result, false)
          this.refresh(true);
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    // 新增
    rowCreate(data) {
      rowBatchCreate(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(message || $i18n.t("common.addSuccess"));
          this.visible = false;
          this.refresh();
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    // 修改详情
    editInfo(id, flag) {
      this.changeMaster(flag);
      this.loading = true;
      getInfoByOrderNo(id, flag)
        .then(async (res) => {
          this.formDataDialog = res.data.result;
          this.visible = true;
          this.mesKtInTaskDetailVoList = res.data.result.mesKtInTaskDetailVos
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleEditBatch(data){
      let flag = true;
      data.mesKtInTaskDetailVos.some((item,index) => {
        if(item.accountingAmount && item.accountingAmount > 0)
        {
          // if(!item.brand)
          // {
          //   this.$message.warning("第"+(index+1)+"行：请选择品牌");
          //   flag = false
          //   console.warn(flag)
          //   return true
          // }
          // if(!item.unit)
          // {
          //   this.$message.warning("第"+(index+1)+"行：请输入规格");
          //   flag = false
          //   return true
          // }
          if(!item.materialTypeStr)
          {
            this.$message.warning("第"+(index+1)+"行：请选择物料类型");
            flag = false
            return true
          }
          if(!item.supplierName)
          {
            this.$message.warning("第"+(index+1)+"行：请选择供应商");
            flag = false
            return true
          }
        }
      });
      if(flag)
      {
        this.handleSubmitBatch(data)
      }
    },
    handleEdit(row){
      console.log('jieshou ',row)
      if(!row.accountingAmount || row.accountingAmount <= 0)
      {
        this.$message.warning("请输入入库数量");
        return
      }
      // if(!row.brand)
      // {
      //   this.$message.warning("请选择品牌");
      //   return
      // }
      // if(!row.unit)
      // {
      //   this.$message.warning("请输入规格");
      //   return
      // }
      if(!row.materialTypeStr)
      {
        this.$message.warning("请选择物料类型");
        return
      }
      if(!row.supplierName)
      {
        this.$message.warning("请选择供应商");
        return
      }

      this.handleSubmit(row)
    },
    //修改
    rowUpdate(data) {
      this.isLoading = true;
      const newData =
        {
          ...data,
          vinCode: this.formDataDialog.vinCode
        }
      wmsKtInTaskDetail(newData)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(message || $i18n.t("common.operateSuccess"));
          this.editInfo(res.data.result, false)
          this.refresh(true);
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    //删除
    rowDel(data) {
      this.loading = true;
      rowDel(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(message || $i18n.t("common.deleteSuccess"));
          this.refresh();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    //刷新表格数据
    refresh(isReset = true) {
      this.$refs.eleTable.refresh(isReset);
    },
    //跳转至子页面
    goChild(queryParam) {
      let pathParam = "/inbound/wmsInTaskScan";
      this.$router.push({ path: pathParam, query: queryParam });
       // 当前页面以组件方式引入, 点击需要抛出,不进行跳转  by bing
      // if (this.typeInto) {
      //   this.$emit("handerLink", queryParam);
      // } else {
      //   let pathParam = "/inbound/wmsInTaskDetail";
      //   this.$router.push({ path: pathParam, query: queryParam });
      // }
    },
    changeMaster(flag) {
      // this.formDescDialog.isAdd =  true

      // if (flag) {
      //   this.formDescDialog.disabled = true;
      //   // this.formDescDialog.isShowSubmitBtn = false;
      // } else {
      //   this.formDescDialog.disabled = false;
      //   // this.formDescDialog.isShowSubmitBtn = true;
      // }
    },
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    unique(arr) {
      const res = new Map();
      return arr.filter(
        (item) => !res.has(item.goodsCode) && res.set(item.goodsCode, 1)
      );
    },
    // 过账
    rowAccount(data) {
      this.loading = true;
      rowAccount(data)
        .then((res) => {
          const message = res.data.message || $i18n.t("operateSuccess");
          this.$message.success(message);
          this.refresh();
        })
        .finally(() => {
          this.loading = false;
        });
    },
  },
};
</script>
